Applications, Examples and Libraries

Share your work here

Let N=pq be an odd semi-prime; What is the distribution of  integers that has a common divisor with N. We have shown that the distribution in [1,N-1] is a symmetric one, and there exsits a multiple of p lying to a multiple of q. We post the Maple source here.

 

gap := proc(a, b) return abs(a - b) - 1; end proc

HostsNdivisors := proc(N)

local i, j, g, d, L, s, t, m, p, q, P, Q, np, nq;

m := floor(1/2*N - 1/2);

L := evalf(sqrt(N));

P := Array();

Q := Array();

s := 1; t := 1;

for i from 3 to m do

   d := gcd(i, N);

    if 1 < d and d < L then P(s) := i; s++;

    elif L < d then Q(t) := i; t++; end if;

end do;

  np := s - 1;

  nq := t - 1;

 for i to np do printf("%3d,", P(i)); end do;

  printf("\n");

  for i to nq do printf("%3d,", Q(i)); end do;

  printf("\n gaps: \n");

  for i to np do

     for j to nq do

      p := P(i); q := Q(j);

      g := gap(p, q);

      printf("%4d,", g);

  end do;

    printf("\n");

end do;

end proc

 

HostOfpq := proc(p, q)

local alpha, s, t, g, r, S, T, i, j;

   S := 1/2*q - 1/2;

   T := 1/2*p - 1/2;

   alpha := floor(q/p);

    r := q - alpha*p;

   for s to S do

     for t to T do

       g := abs((t*alpha - s)*p + t*r) - 1;

        printf("%4d,", g);

      end do;

     printf("\n");

 end do;

end proc

 

MapleSource.pdf

MapleSource.mw

 



(EDITED 2024/03/11  GMT 17H)

In a recent Question@cq mentionned in its last reply "In fact, I wanted to do parameter sensitivity analysis and get the functional relationship between the [...] function and [parameters]. Later, i will study how the uncertainty of [the parameters] affects the [...] function".
I did not keep exchanging further on with @cq, simply replying that I could provide it more help if needed.

In a few words the initial problem was this one:

  • Let X_1 and X_2 two random variables and G the random variable defined by  G = 1 - (X_1 - 1)^2/9 - (X_2 - 1)^3/16.
     
  •  X_1 and X_2 are assumed to be gaussian random variables with respective mean and standard deviation equal to (theta_1, theta_3) and (theta_2, theta_4).
     
  • The four theta parameters are themselves assumed to be realizations of four mutually independent uniform random variables Theta_1, ..., Theta_4 whose parameters are constants.
     
  • Let QOI  (Quantity Of Interest) denote some scalar statistic of G (for instance its Mean, Variance, Skweness, ...).
    For instance, if QOI = Mean(G), then  QOI expresses itself as a function of the four parameters theta_1, ..., theta_4.
    The goal of @cq is to understand which of those parameters have the greatest influence on QOI.


For a quick survey of Sensitivity Analysys (SA) and a presentation of some of the most common strategies see Wiki-Overview


The simplest SA is the Local SA (LSA) we are all taught at school: having chosen some reference point P in the [theta_1, ..., theta_4] space the 1st order partial derivatives d[n] = diff(QOI, theta_n) expressed at point P give a "measure" (maybe after some normalization) of the sensitivity, at point P, of QOI regardibg each parameter theta_n.


A more interesting situation occurs when the parameters can take values in a neighorhood of  P which is not infinitesimal, or more generally in some domain without reference to any specific point P.
That is where Global SA (GSA) comes into the picture.
While the notion of local variation at some point P is well established, GSA raises the fundamental question of how to define how to measure the variation of a function over an arbitrary domain?
Let us take a very simple example while trying to answer this question "What is the variation of sin(x) over [0, 2*Pi]?"

  1. If we focus on the global trend of sin(x)  mean there is no variation at all.
  2. If we consider peak-to-peak amplitude the variation is equal to 2.
  3. At last, if we consider L2 norm the variation is equal to Pi.
    (but the constant function x -> A/sqrt(2) has the same L2 norm but it is flat, and in some sense les fluctuating). 


Statisticians are accustomed to use the concept of variance as a measure to quantify the dispersion of a random variable. At the end of the sixties  one of them, Ilya Meyerovich Sobol’,  introduced the notion of Variance-Based GSA as the key tool to define the global variation of a function. This notion naturally led to that of Sobol' indices as a measure of the sensitivity of a funcion regarding one of its parameters or, which most important, regarding any combination (on says interaction) of its parameters.

The aim of this post is to show how Sobol' indices can be computed when the function under study has an analytic expression.
 

The Sobol' analysis is based on an additive decomposition of this function in terms of 2^P mutually orthogonal fiunctions where P is the number of its random parameters.
This decomposition and the ensuing integrations whose values will represent the Sobol' indices can be done analytically in some situation. When it is no longer the case specific numerical estimation methods have to be used;


The attached file contains a quite generic procedure to compute exact Sobol' indices and total Sobol' indices for a function whose parameters have any arbitrary statistical distribution.
Let's immediately put this into perspective by saying that these calculations are only possible if Maple is capable to find closed form expressions of some integrals, which is of course not always the case.

A few examples are also provided, including the one corresponding to @cq's original question.
At last two numerical estimation methods are presented.

SOBOL.mw

 

A checkered figure is a connected flat figure consisting of unit squares. The problem is to cut this figure into several equal parts (in area and shape). Cuts can only be made on the sides of the cells. In mathematics, such figures are called polyominoes, and the problem is called the tiling of a certain polyomino with copies of a single polyomino. See https://en.wikipedia.org/wiki/Polyomino

Below are 3 examples of such figures:

We will define such figures by the coordinates of the centers of the squares of which it consists. These points must lie in the first quarter, and points of this figure must lie on each of the coordinate axes.

Below are the codes for two procedures named  CutEqualParts  and  Picture . Required formal parameters of the first procedure: set  S  specifies the initial figure, r is the initial cell for generating subfigures, m is the number of parts into which the original figure needs to be divided. The optional parameter  s  equals (by default onesolution) or allsolutions. The starting cell  r  should be the corner cell of the figure. Then the set of possible subshapes for partitioning will be smaller. If there are no solutions, then the empty set will be returned. The second procedure  Picture  returns a picture of the obtained result as one partition (for a single solution) or in the form of a matrix if there are several solutions. In the second case, the optional parameter  d  specifies the number of rows and columns of this matrix.

restart;
CutEqualParts:=proc(S::set(list),r::list,m::posint, s:=onesolution)
local OneStep, n, i1, i2, j1, j2, R, v0, Tran, Rot, Ref, OneStep1, M, MM, MM1, T, T0, h, N, L;
n:=nops(S)/m;
if irem(nops(S), m)<>0 then error "Should be (nops(S)/m)::integer" fi;
if not (r in S) then error "Should be r in S" fi;
if m=1 then return {S} fi;
if m=nops(S) then return map(t->{t}, S) fi;
i1:=min(map(t->t[1],select(t->t[2]=0,S)));
i2:=max(map(t->t[1],select(t->t[2]=0,S)));
j1:=min(map(t->t[2],select(t->t[1]=0,S)));
j2:=max(map(t->t[2],select(t->t[1]=0,S)));
OneStep:=proc(R)
local n1, R1, P, NoHoles;
R1:=R;
n1:=nops(R1);
R1:={seq(seq(seq(`if`(r1 in S and not (r1 in R1[i]) , subsop(i={R1[i][],r1}, R1)[],NULL),r1=[[R1[i,j][1],R1[i,j][2]-1],[R1[i,j][1]+1,R1[i,j][2]],[R1[i,j][1],R1[i,j][2]+1],[R1[i,j][1]-1,R1[i,j][2]]]), j=1..nops(R1[i])), i=1..n1)};
NoHoles:=proc(s)
local m1, m2, M1, M2, M;
m1:=map(t->t[1],s)[1]; M1:=map(t->t[1],s)[-1];
m2:=map(t->t[2],s)[1]; M2:=map(t->t[2],s)[-1];
M:={seq(seq([i,j],i=m1..M1),j=m2..M2)}; 
if ormap(s1->not (s1 in s) and `and`(seq(s1+t in s, t=[[1,0],[-1,0],[0,1],[0,-1]])), M) then return false fi;
true;
end proc:
P:=proc(t)
if `and`(seq(seq(seq(([i,0] in t) and ([j,0] in t) and not ([k,0] in t) implies not ([k,0] in S), k=i+1..j-1), j=i+2..i2-1), i=i1..i2-2)) and `and`(seq(seq(seq(([0,i] in t) and ([0,j] in t) and not ([0,k] in t) implies not ([0,k] in S), k=i+1..j-1), j=i+2..j2-1), i=j1..j2-2))  then true else false fi;
end proc:
select(t->nops(t)=nops(R[1])+1 and NoHoles(t) and P(t) , R1);
end proc:
R:={{r}}:
R:=(OneStep@@(n-1))(R):
v0:=[floor(max(map(t->t[1], S))/2),floor(max(map(t->t[2], S))/2)]:
h:=max(v0);
Tran:=proc(L,v) L+v; end proc:
Rot:=proc(L, alpha,v0) <cos(alpha),-sin(alpha); sin(alpha),cos(alpha)>.convert(L-v0,Vector)+convert(v0,Vector); convert(%,list); end proc:
Ref:=proc(T) map(t->[t[2],t[1]], T); end proc:
OneStep1:=proc(T)
local T1, n2, R1;
T1:=T; n2:=nops(T1);
T1:={seq(seq(`if`(r1 intersect `union`(T1[i][])={}, subsop(i={T1[i][],r1}, T1), NULL)[], r1=MM1 minus T1[i]), i=1..n2)};
end proc:
N:=0; 
for M in R do
MM:={seq(seq(seq(map(t->Tran(Rot(t,Pi*k/2,v0),[i,j]),M),i=-h-1..h+1),j=-h-1..h+1),k=0..3),seq(seq(seq(map(t->Tran(Rot(t,Pi*k/2,v0),[i,j]),Ref(M)),i=-h-1..h+1),j=-h-1..h+1), k=0..3)}:
MM1:=select(t->(t intersect S)=t, MM):
T:={{M}}:
T:=(OneStep1@@(m-1))(T):
T0:=select(t->nops(t)=m, T):
if T0<>{} then if s=onesolution then return T0[1] else N:=N+1;
 L[N]:=T0[] fi; fi; 
od:
L:=convert(L,list);
if L[]::symbol then return {} else L fi;
end proc:
Picture:=proc(L::{list,set},Colors::list,d:=NULL)
local r;
uses plots, plottools;
if L::set or (L::list and nops(L)=1) or d=NULL then return
display( seq(polygon~(map(t->[[t[1]-1/2,t[2]-1/2],[t[1]+1/2,t[2]-1/2],[t[1]+1/2,t[2]+1/2],[t[1]-1/2,t[2]+1/2]] ,`if`(L::set,L[j],L[1][j])), color=Colors[j]),j=1..nops(Colors)) , scaling=constrained, size=[800,600]) fi;
if d::list then r:=irem(nops(L),d[2]);
if r=0 then return
display(Matrix(d[],[seq(display(seq(polygon~(map(t->[[t[1]-1/2,t[2]-1/2],[t[1]+1/2,t[2]-1/2],[t[1]+1/2,t[2]+1/2],[t[1]-1/2,t[2]+1/2]]  ,L[i,j]), color=Colors[j]),j=1..nops(Colors)), scaling=constrained, size=[400,300], axes=none), i=1..nops(L))])) else
display(Matrix(d[],[seq(display(seq(polygon~(map(t->[[t[1]-1/2,t[2]-1/2],[t[1]+1/2,t[2]-1/2],[t[1]+1/2,t[2]+1/2],[t[1]-1/2,t[2]+1/2]]  ,L[i,j]), color=Colors[j]),j=1..nops(Colors)), scaling=constrained, size=[400,300], axes=none), i=1..nops(L)), seq(plot([[0,0]], axes=none, size=[10,10]),k=1..d[2]-r)]))  fi; fi; 
end proc:

Examples of use for figures 1, 2, 3
In the first example for Fig.1 we get 4 solutions for m=4:

S:=({seq(seq([i,j], i=0..4), j=0..2)} union {[2,3],[3,3],[3,4]}) minus {[0,0],[0,1]}:
L:=CutEqualParts(S,[0,2],4,allsolutions);
C:=["Cyan","Red","Yellow","Green"]:
nops(L);
Picture(L,C,[2,2]);

In the second example for Fig.2 for m=2, we get 60 solutions (the first 16 are shown in the figure):

S:={seq(seq([i,j], i=0..4), j=0..4)} minus {[2,2]}:
L:=CutEqualParts(S,[0,0],2,allsolutions):
nops(L);
 C:=["Cyan","Red"]:
Picture(L[1..16],C,[4,4]);


In the third example for Fig.3 and  m=2  there will be a unique solution:

S:={seq(seq([i,j], i=0..5), j=0..3)}  minus {[5,0],[4,2]} union {[1,4],[2,4]}:
L:=CutEqualParts(S,[0,0],2):
 C:=["Cyan","Red"]:
Picture(L,C);


Addition. It is proven that the problem of tiling a certain polyomino with several copies of a single polyomino is NP-complete. Therefore, it is recommended to use the CutEqualParts procedure when the numbers  nops(S)  and  nops(S)/m  are relatively small (nops(S)<=24  and nops(S)/m<=12), otherwise the execution time may be unacceptably long.

Cutting_equal_parts.mw

A ball on a turntable can move in circles instead of falling off the edge (provided the initial conditions are appropriate). The effect was demonstrated in a video and can be simulated with MapleSim. The amination below shows a simulation of a frictionless case (falling off the table) and the case with a coefficient of friction of one.

Also demonstrated in the video: Tilting the table leads to a sideward (not a downhill) movement of the ball.

The presenter of the video noted that in the untilted state, the ball eventually drifts off the table, attributing this to slippage. This drift is also observable in the animation above, where the ball starts moving in a spiral, whereas in a Maple simulation (below to the left), the ball follows a perfect circle. Only after optimizing contact and initial conditions, MapleSim produced a result (using the same parameters) that exhibits a similar circle, with a slight difference in angular orientation after completing two revolutions about the center of the circle.

 

Some observations on the MapleSim model:

  • The results only slightly depend on the solvers. Numerical inaccuracies do not seem to be the reason for the difference in orientation. (Edit: see update below for the reason).
  • The ball bounces up and down in the MapleSim simulation (0.0025 of the balls radius). The bouncing is caused by the fact that the initial position of the ball is above the elastic equilibrium position with respect to the table (the elastic contact makes the ball sink in a bit). Adding damping in the settings of the contact element attenuates this effect and reduces the drift.
  • Drift is not observable anymore if in the contact element setting for "kmu" (smoothness coefficient of sliding friction) is set to larger values (above 10 in this example). This is an indication that sliding friction occurs during the simulation.
  • Choosing the equilibrium position as initial condition for the ball does not prevent initial bouncing because MapleSim sets an initial velocity for the ball that is directed away from the table. I did not manage to enforce strictly zero velocity. Maybe someone can tell why that is and how to set MapleSim to start the simulation without vertical velocity. (Edit: see update below for the reason).
  • Assuming an initial velocity towards the contact to cancel the initial vertical velocity set by MapleSim substantially reduces bouncing and increases the diameter of the circle. This finally leads to a diameter that matches the Maple simulation. Therefore the initial bouncing combined with slippage seems to dissipate energy which leads to smaller circles. Depending on the contact settings and initial conditions for vertical movement the diameter of the circle varied moderately by about 15%.

In summary, MapleSim can be parametrized to simulate an ideal case without slippage. From there it should be possible to tune contact parameters to closely reproduce experiments where parameters are often not well known in advance.  

Some thoughts for future enhancement of MapleSim:

  • In the model presented here, a patterned ball would have been helpful to visualize the tumbling movement of the ball. Marking two opposite sides of the ball with colored smaller spheres is a fiddly exercise that does not look nice.
  • A sensor component that calculates the energy of a moving rigid body would have helped identifying energy loss of the system. Ideally the component could have two ports for the rotational and translational energy components. I see professional interest in such calculations and not only educational value for toy experiments.
  • A port for slippage on the contact elements would have helped understanding where slippage occurs. Where slippage is, there is wear and this is also of interest for industrial applications.

Turntable_Paradox.msim (contains parameter sets for the above observations)

February 2nd is Groundhog Day in North America. A day when we look to small marmots to prognosticate the weather. If the groundhog sees its shadow when it emerges from its burrow, then it predicts 6 more weeks of winter, and if not, then spring begins today! Unfortunately there are many official weather predicting groundhogs. Fortunately, the excellent website Groundhog-Day.com tracks each of their predictions. Unfortunately, it doesn't tell you which groundhog to trust. Fortunately, it has an API and we can take the data and map it in Maple:

This map assumes that each groundhog's prediction is valid at it's exact geographic coordinates, but that it's predictive powers fall off in inverse proportion to the distance away.  So, exactly halfway between a groundhog predicting early spring, and one predicting 6 more weeks of winter, we expect 3 more weeks of winter.  I handle that with Maple's Interpolation:-InverseDistanceWeightedInterpolation command with a radius of 1500 miles.  I plot a contourplot of that interpolating function, and then display it with the world map in DataSets:-Builtin:-WorldMap to generate the image above.

All the code to do that can be found in the following worksheet which also using the URL packaget to fetch the most recent groundhog data possible from the website.

Groundhog-Map.mw

I've commented out a few lines that you might use to explore other possible maps.  You can filter to file to just include real living groundhogs and not all the other precitions (some from puppets, some from other animals) if you find that more trust worthy. You might also prefer to change the interpolation command, one of my collegues suggests that Interpolation:-NaturalNeighborInterpolation might be a better choice.

To Scan Math with the Maple Calculator and show solution steps in Maple:

1. first scan some math with the calculator (right-clik on any image below and open in a new tab to see it larger)

2. Maple calculator immediately shows the solution if that is what you are looking for:

3. Calculator gives options to show the solution steps in the calculator itself ( footprint button in top-right) 

4. Or to upload the math to the MapleCloud (cloud icon with up arrow)

5. Once the math is uploaded, MapleCloud can be loaded on a desktop computer and the file opened from your account's Maple Calculator group of files:

6. Again, the solution and some more details are visible on Maple Cloud:

7. To open this math in Maple, click the blue button to Download the file.

The downloaded file can then be loaded in Maple:

8. The Maple commands to solve this math are shown, and the result. 

To show steps in Maple at this point, convert the math to inert form, then run the Student:-Calculus1:-ShowSolution() command on it:

Ex := Int(3.(x^2), x = 0 .. 7)

Int(3*x^2, x = 0 .. 7)

(1)

Integrate

 

The solution to this integral is:

int(3*x^2, x = 0 .. 7)

343

(1.1)

Student:-Calculus1:-ShowSolution(Ex)

"[[,,"Integration Steps"],[,,(&int;)[0]^73 x^2 &DifferentialD;x],["&EmptyVerySmallSquare;",,"1. Apply the" "constant multiple" "rule to the term" &int;3 x^2 &DifferentialD;x],[,"?","Recall the definition of the" "constant multiple" "rule"],[,,&int;[] f(x) &DifferentialD;x=[] (&int;f(x) &DifferentialD;x)],[,"?","This means:"],[,,&int;3 x^2 &DifferentialD;x=3 (&int;x^2 &DifferentialD;x)],[,,"We can rewrite the integral as:"],[,,3 ((&int;)[0]^7x^2 &DifferentialD;x)],["&EmptyVerySmallSquare;",,"2. Apply the" "power" "rule to the term" &int;x^2 &DifferentialD;x],[,"?","Recall the definition of the" "power" "rule, for n" "<>" "-1"],[,,&int;x^[] &DifferentialD;x=[]],[,"?","This means:"],[,,&int;x^2 &DifferentialD;x=[]],[,"?","So,"],[,,&int;x^2 &DifferentialD;x=(x^3)/3],[,"?","Apply limits of definite integral"],[,,[]-([])],[,,"We can rewrite the integral as:"],[,,343]]6""

(2)

Download MapleCalculatorMathCloudUpload.mw

I'm an engineer and when showing results of calculations, some values will display as fractions, and I would prefer that instead floating numbers are displayed.  Also, there is kind of a quirk where if the multiplier of a unit is 1, the result displays as a unit only. I would prefer to see 1*A rather than A.

I wrote this simple proc to convert a value with or without attached unit to a floating point number if it is a fraction or if it has a unit and the coefficient is 1.

Let me know if there is a more elegant way to do this or you have any suggestions or questions.

   unrationalize := proc(x)
        local 
            returnval,
            localcoeff,
            localunit
        ;
        description
            "Converts a fractional number to float",
            "Units are supported"
        ;
        if type(x, fraction) or type(x, with_unit(fraction)) then 
            returnval := evalf(x)
        elif type(x, with_unit(1, 'localcoeff', 'localunit')) then
            returnval :=  evalf(localcoeff)*localunit
        else 
            returnval := x;
        end if;
        return returnval;
    end  proc;
# Testing the proc
list1 := [1/2, 1/2*Unit(('A')/('V')), 1, Unit('A')];
listDescription := ["Fraction", "Fraction with Unit", "Unity", "Unity with Unit"];
for i, myValue in list1 do
    [listDescription[i], "evalf:", evalf(myValue), "unrationalize:", unrationalize(myValue)];
end do;

Curve sketching is an important skill for all calculus students to learn. In an era where technology is increasingly relied upon to perform mathematical computations and representations, maintaining fundamental skills such as curve sketching is more important than ever.

The new “Curve Sketching” collection is now available on Maple Learn. This collection provides background information on the process of curve sketching and opportunities to put this knowledge into practice. By starting with the “Curve Sketching Guide” and “Relationships Between Derivatives” documents, students are exposed to observational and computational strategies for drawing a function and its 1st and 2nd derivatives.

After looking through these documents, students can begin to practice sketching by observing and interpreting graphical properties with the “Sketch Derivative From Function Graph”, “Sketch Second Derivative From Function Graph”, and “Sketch Function From Derivative Graphs” activities:

Once a student has mastered extracting sketching information by graphical observation, they are ready for the next step: extracting information from a function’s definition. At this point, the student is ready to try sketching from a blank canvas with the “Sketch Curve From Function Definition” activity:

This collection also has activities for students below the calculus level. For example, the “Curve Sketching Quadratics Activity”, can be completed using only factoring strategies:

Whether you are a quadratics rookie or a calculus pro, this collection has an interactive activity to challenge your knowledge. Have fun sketching!

My friend and colleague Nic Fillion and I are writing another book, this one on perturbation methods using backward error analysis (and Maple).  We have decided to make the supporting materials available by means of Jupyter notebooks with a Maple kernel (there are some Maple worksheets and workbooks already, but going forward we will use Jupyter).

The presentation style is meant to aid reproducibility, and to allow others to solve related problems by changing the scripts as needed.

The first one is up at 

https://github.com/rcorless/Perturbation-Methods-in-Maple

Comments very welcome.  This particular method is a bit advanced in theory (but it's very simple in practice, for weakly nonlinear oscillators).  I haven't coded for efficiency and there may be some improvements possible ("may" he says, sheesh).  Comments on that are also welcome.

-r

In the most recent issue of Maple Transactions, I published (with David Jeffrey, and with a student named Johan Joby) a paper that used Jupyter Notebook with a Maple kernel as the main vehicle.  Have a look, and let me know what you think.

Two-cycles in the infinite exponential tower

 

restart;

plots:-inequal([x^2+y^2<100, x+y>Pi]);      # ?,  evalf(Pi) ok

Error, (in ReasonableDomain:-Implicit) invalid input: ReasonableDomain:-Recorder:-AddPoint expects its 2nd argument, point, to be of type list(numeric), but received [Pi, 0]

 

plots:-inequal([x^2+y^2<100, x+y>sqrt(3)]); # ?

Error, (in ReasonableDomain:-Implicit) invalid input: ReasonableDomain:-Recorder:-AddPoint expects its 2nd argument, point, to be of type list(numeric), but received [3^(1/2), 0]

 

solve({x^2+y^2<100, x+y>Pi});               # ?

Warning, solutions may have been lost

 

solve({x^2+y^2<100, x+y>sqrt(10)});         # ?

Warning, solutions may have been lost

 

solve({x^2+y^2<100, x+y>4}, [x,y]);         # OK

[[x < 2+46^(1/2), 2-46^(1/2) < x, y < (-x^2+100)^(1/2), 4-x < y], [x = 2+46^(1/2), y < -2+46^(1/2), 2-46^(1/2) < y], [x < 10, 2+46^(1/2) < x, y < (-x^2+100)^(1/2), -(-x^2+100)^(1/2) < y]]

(1)

solve({x^2+y^2<100, x+y>a}, [x,y]) assuming 3<a, a<5;              #?

[]

(2)

solve({x^2+y^2<100, x+y>a}, [x,y], parametric) assuming 3<a, a<5;  # OK

[[x = (1/2)*a+(1/2)*(-a^2+200)^(1/2), (1/2)*a-(1/2)*(-a^2+200)^(1/2) < y, y < -(1/2)*a+(1/2)*(-a^2+200)^(1/2)], [(1/2)*a-(1/2)*(-a^2+200)^(1/2) < x, x < (1/2)*a+(1/2)*(-a^2+200)^(1/2), a-x < y, y < (-x^2+100)^(1/2)], [(1/2)*a+(1/2)*(-a^2+200)^(1/2) < x, x < 10, -(-x^2+100)^(1/2) < y, y < (-x^2+100)^(1/2)]]

(3)


Download bugs-irrationals.mw

Why this post
This work was intended to be a simple reply to a question asked a few days ago.
At some point, I realised that the approach I was using could have a more general interest which, in my opinion, was worth a post.
In a few words, this post is about solving an algebra problem using a method originally designed to tackle statistical problems.

The Context
Recently @raj2018 submitted a question I'm going to resume this way:

Let S(phi ;  beta, f) a function of phi parameterized by beta and f.
Here is the graph of S(phi ;  0.449, 0.19)  @raj2018 provided

@raj2018 then asked how we can find other values (A, B)  of values for (beta, f) such that the graph of S(phi, A, B) has the same aspect of the graph above.
More precisely, let phi_0 the largest strictly negative value of phi such that  S(phi_0, A, B) = 0.
Then  S(phi, A, B) must be negative (strictly negative?) in the open interval (phi_0, 0), and must have exactly 3 extrema in this range.
I will said the point  (A, B) is admissible is S(phi, A, B) verifies thess conditions

The expression of S(phi, A, B) is that complex that it is likely impossible to find an (several?, all?) admissible point using analytic developments.

The approach

When I began thinking to this problem I early thought to find the entire domain of admissible points: was it something possible, at least with some reasonable accuracy? 

Quite rapidly I draw an analogy with an other type of problems whose solution is part of my job: the approximate construction of the probability density function (PDF) of multivariate random variables (obviously this implies that no analytical expression of this PDF is available). This is a very classical problem in Bayesian Statistics, for instance when we have to construt an approximation of a posterior PDF.

To stick with this example and put aside the rare situations where this PDF can be derived analytically, building a posterior PDF is largely based on specific numerical methods. 
The iconic one is known under the generic name MCMC  which stands for Markov Chain Monte Carlo.

Why am I speaking about MCMC or PDF or even random variables?
Let us consider some multivariate random variable R whose PDF as a constant on some bounded domain D and is equal to 0 elsewhere. R is then a uniform random variable with support supp(R) = D.
Assuming the domain Adm of admissible (beta, f) is bounded, we may  think of it as the support of some uniform random variable. Following this analogy we may expect to use some MCMC method to "build the PDF of the bivariate random variable (beta, f)", otherwise stated "to capture​​​​​​ the boundary of​ Adm".

The simplest MCMC method is the Metropolis-Hastings algorithm (MH).
In a few simple words MH builds a Markov chain this way:

  1. Let us assume that the chain already contains elements e1, ..., en.
    Let  f  some suitable "fitness" function (whose nature is of no importance right now).
  2. A potential new element c is randomly picked in some neighborhood or en.
  3. If the ratio (c) / (en) is larger than 1, we decide to put c into the chain (thus en+1 = c) otherwise we leave it to chance to decide whether or not c iis put into the chain.
    If chance decides the contrary,  then en is duclicated (thus en+1 = en).


MH is not the most efficient MCMC algorithm but it is efficient enough for what we want to achieve.
The main difficulty here is that there is no natural way to build the fitness function  f , mainly because the equivalent random variable I talked about is a purely abstract construction.

A preliminary observation is that if S(phi, beta, f) < 0 whatever phi in (phi_0, 0), then S has an odd number of extrema in (phi_0, 0). The simplest way to find these extrema is to search for the zeros of the derivative S' of S with respect to phi, while discardinq those where the second derivative can reveal "false" extrema where both S'' of S is null (I emphasize this last point because I didn't account for it in attached file).
The algorithm designed in this file probably misses a few points for not checking if S''=0, but it is important to keep in mind that we don't want a complete identification of  Adm but just the capture of its boundary.
Unless we are extremely unlucky there is only a very small chance that omitting to check if S''=0 will deeply modify this boundary.


How to define function f  ?
What we want is that  f (c) / (en) represents the probability to decide wether c is an admissible point or not. In a Markov chain this  ratio represents how better or worse c is relatively to en, and this is essential for the chain to be a true Markov chain.
But as our aim is not to build a true Markov chain but simply a chain which looks like a Markov chain, we we can take some liberties and replace  f (c) / (en) by some function  g(c) which quantifies the propability for c to be an admissible couple. So we want that  g(c) = 1 if  S(phi, c) has exactly M=3 negative extrema and  g(c) < 1 if M <> 3.
The previous algorihm transforms into:

  1. Let us assume that the chain already contains elements e1, ..., en.
    Let  g  a function which the propability that element is admissible
  2. A potential new element c is randomly picked in some neighborhood or en.
  3. If the ratio g(c) is larger than 1, we decide to put c into the chain (thus en+1 = c) otherwise we leave it to chance to decide whether or not c iis put into the chain.
    If chance decides the contrary,  then en is duclicated (thus en+1 = en).

This algorithm can also be seen as a kind of genetic algorithm.

A possible choice is  g(c)= exp(-|3-M|).
In the attached file I use instead the expression g(c) = (M + 1) / 4 fo several reasons:

  • It is less sharp at M=3 and thus enables more often to put c into the chain, which increases its exploratory capabilities.
  • The case M > 3, which no preliminary investigation was able to uncover, is by construction eliminated in the procedure Extrema which use an early stopping strategy (if as soon as more than M=3 negative extrema are found the procedure stops).


The algorithm I designed basically relies upon two stages:

  1. The first one is aimed to construct a "long" Markov-like chain ("long" and not long because Markov chains are usually much longer than those I use).
    There are two goals here:
    1. Check if Adm is or not simply-connected or not (if it has holes or not).
    2. Find a first set of admissible points that can be used as starting points for subsequent chains.
       
  2. Run several independent Markov-like chains from a reduced set of admissible points.
    The way this reduced set is constructed depends on the goal to achieve:
    1. One may think of adding points among those already known in order to assess the connectivity of Adm,
    2. or refinining the boundary of Adm.

These two concurent objectives are mixed in an ad hoc way depending on the observation of the results already in hand.


We point here an important feature of MCMC methods: behind their apparent algorithmic simplicity, it is common that high-quality results can only be obtained efficiently at the cost of problem-dependent tuning.

A last word to say that after several trials and failures I found it simpler to reparameterize the problems in terms of (phi_0, f) instead of (beta, f).

Codes and results

Choice g(c) = (M + 1) / 4 
The code : Extrema_and_MCMC.mw

To access the full results I got load this m file (do not bother its extension, Mapleprimes doesn't enable uploading m files) MCMC_20231209_160249.mw (save it and change it's extension in to m instead mw)

EDITED: choice  g(c)= exp(-|3-M|)
Here are the files contzining the code and the results:
Extrema_and_MCMC_g2.mw
MCMC_20231211_084053.mw

To ease the comparison of the two sets of results I used the same random seeds inn both codes.
Comparing the results got around the first admissible point is straightforward.
It's more complex for @raj2018's solution because the first step of the algorithim (drawing of a sibgle chain of length 1000) finds six times more admissible point with g(c)= exp(-|3-M|) than with g(c) = (M + 1) / 4.                                 

 

A new “Sudoku Puzzle” document is now on Maple Learn! Sudoku is one of the world’s most popular puzzle games and it is now ready to play on our online platform. 

This document is a great example of how Maple scripts can be used to create complex and interactive content. Using Maple’s built-in DocumentTools:-Canvas package, anyone can build and share content in Maple Learn. If you are new to scripting, a great place to start is with one of the scripting templates, which are accessible through the Build Interactive Content help page. In fact, I built the Sudoku document script by starting from the “Clickable Plots” template.

A Sudoku puzzle is a special type of Latin Square. The concept of a Latin Square was introduced to the mathematical community by Leonard Euler in his 1782 paper, Recherches sur une nouvelle espèce de Quarrés, which translates to “Research on a new type of square”. A Latin Square is an n by n square array composed of n symbols, each repeated exactly once in every row and column. The Sudoku board is a Latin Square where n=9, the symbols are the digits from 1 to 9,  and there is an additional requirement that each 3 by 3 subgrid contains each digit exactly once. 

Mathematical research into Sudoku puzzles is still ongoing. While the theory about Latin Squares is extensive, the additional parameters and relative novelty of Sudoku means that there are still many open questions about the puzzle. For example, a 2023 paper from Peter Dukes and Kate Nimegeers examines Sudoku boards through the lenses of graph theory and linear algebra.

The modern game of Sudoku was created by a 74-year-old Indiana retiree named Howard Garnes in 1979 and published under the name “Number Place”. The game had gained popularity in Japan by the mid-1980s, where it was named “Sudoku,” an abbreviation of the phrase “Sūji wa dokushin ni kagiru,” which means “the numbers must be single”.

Today, Sudoku is a worldwide phenomenon. This number puzzle helps players practice using their logical reasoning, short-term memory, time management, and decision-making skills, all while having fun. Furthermore, research from the International Journal of Geriatric Psychiatry concluded that doing regular brain exercises, like solving a Sudoku, is correlated with better brain health for adults over 50 years old. Additionally, research published in the BMJ medical journal suggests that playing Sudoku can help your brain build and maintain cognition, meaning that mental decline due to degenerative conditions like Alzheimer’s would begin from a better initial state, and potentially delay severe symptoms. However, playing Sudoku will by no means cure or prevent such conditions.

If you are unfamiliar with the game of Sudoku, need a refresher on the rules, or want to improve your approach, the “Sudoku Rules and Strategies” document is the perfect place to start. This document will teach you essential strategies like Cross Hatching:

And Hidden Pairs:

After reading through this document, you will have all the tools you need to start solving puzzles with the “Sudoku Puzzle” document on Maple Learn. 

Have fun solving!

For years I've been angry that Maple isn't capable of formally manipulating random vectors (aka multivariate random variables).
For the record Mathematica does.

The problem I'm concerned with is to create a vector W such that

type(W, RandomVariable)

will return true.
Of course defining W from its components w1, .., wN, where each w is a random variable is easy, even if these components are correlated or, more generally dependent ( the two concepts being equivalent iif all the w are gaussian random variables).
But one looses the property that W is no longer a (multivariate) random variable.
See a simple example here: NoRandomVectorsInMaple.mw

This is the reason why I've developped among years several pieces of code to build a few multivariate random variable (multinormal, Dirichlet, Logistic-Normal, Skew Multivariate Normal, ...).

In the framework of my activities, they are of great interest and the purpose of this post is to share what I have done on this subject by presenting the most classic example: the multivariate gaussian random variable.

My leading idea was (is) to build a package named MVStatistics on the image of the Statistics package but devoted to Multi Variate random variables.
I have already construct such a package aggregating about fifty different procedures. But this latter doesn't merit the appellation of "Maple package" because I'm not qualified to write something like this which would be at the same time perennial, robust, documented, open and conflict-free with the  Statistics package.
In case any of you are interested in pursuing this work (because I'm about to change jobs), I can provide it all the different procedures I built to construct and manipulate multivariate random variables.

To help you understand the principles I used, here is the most iconic example of a multivariate gaussian random variable.
The attached file contains the following procedures

MVNormal
  Constructs a gaussian random vector whose components can be mutually correlated
  The statistics defined in Distribution are: (this list could be extended to other
  statistics, provided they are "recognized" statitics, see at the end of this 
  post):
      PDF
      Mode
      Mean
      Variance
      StandardDeviation = add(s[k]*x[k], k=1..K)
      RandomSample

DispersionEllipse
  Builds and draws the dispersion ellipses of a bivariate gaussia, random vector

DispersionEllipsoid
  Builds and draws the dispersion ellipsoids of a trivariate gaussia, random vector

MVstat
  Computes several statistics of a random vector (Mean, Variance, ...)

Iserlis
  Computes the moments of any order of a gaussian random vector

MVCentralMoment
  Computes the central moments of a gaussian random vector

Conditional
  Builds the conditional random vector of a gaussian random vector wrt some of its components 
  the moments of any order of a gaussian random vector.
  Note: the result has type RandomVariable.

MarginalizeAgainst
  Builds the marginal random vector of a gaussian random vector wrt some of its components 
  the moments of any order of a gaussian random vector.
  Note: the result has type RandomVariable.

MardiaNormalityTest
  The multi-dimensional analogue of the Shapiro-Wilks normality test

HZNormalityTest
  Henze-Zirkler test for Multivariate Normality

MVWaldWolfowitzTest
  A multivariate version of the non-parametrix Wald-Folfowitz test

Do not hesitate to ask me any questions that might come to mind.
In particular, as Maple introduces limitations on the type of some attributes (for instance Mean  must be of algebraic type), I've been forced to lure it by transforming vector or matrix quantities into algebraic ones.
An example is

Mean = add(m[k]*x[k], k=1..K)

where m[k] is the expectation of the kth component of this random vector.
This implies using the procedure MVstat to "decode", for instance, what Mean returns and write it as a vector.

MultivariateNormal.mw

About the  statistics ths Statistics:-Distribution constructor recognizes:
To get them one can do this (the Normal distribution seems to be the continuous one with the most exhaustive list os statistics):

restart
with(Statistics):
X := RandomVariable(Normal(a, b)):
attributes(X);
      protected, RandomVariable, _ProbabilityDistribution

map(e -> printf("%a\n", e), [exports(attributes(X)[3])]):
Conditions
ParentName
Parameters
CharacteristicFunction
CDF
CGF
HodgesLehmann
Mean
Median
MGF
Mode
PDF
RousseeuwCrouxSn
StandardDeviation
Support
Variance
CDFNumeric
QuantileNumeric
RandomSample
RandomSampleSetup
RandomVariate
MaximumLikelihoodEstimate

Unfortunately it happens that for some unknown reason a few statistics cannot be set by the user.
This is for instance the case of Parameters serious consequences in certain situations.
Among the other statistics that cannot be set by the user one finds:

  • ParentName,
  • QuantileNumeric  whose role is not very clear, at least for me, but which I suspect is a procedure which "inverts" the CDF to give a numerical estimation of a quantile given its probability.
    If it is so accessing  QuantileNumeric would be of great interest for distributions whose the quantiles have no closed form expressions.
  • CDFNumeric  (same remark as above)

Finally, the statistics Conditions, which enables defining the conditions the elements of Parameters must verify are not at all suited for multivariate random variables.
It is for instance impossible to declare that the variance matrix (or the correlation matrix) is a square symmetric positive definite matrix).

A Flow and Maple user wonders why Maple Flow may evaluate to high-precision, floating point numbers compared to the same commands used in Maple that evaluate to simple, concise answers.

 

 

We suggest the same results can be achieved by toggling the numeric/symbolic evaluation mode toggle in the Flow math container(s)

 

 

primes-flow-evaluation-modes.flow

 

For more information, please see section 3.5 of the Maple Flow User Manual (Numeric and Symbolic Evaluation Modes). 

1 2 3 4 5 6 7 Last Page 1 of 71